package com.ruoyi.medicine.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;


import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.medicine.domain.MedicineOption;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.medicine.domain.DocStocks;
import com.ruoyi.medicine.service.IDocStocksService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.service.ISysDictTypeService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;





/**
 * 商品库存Controller
 *
 * @author ruoyi
 * @date 2025-08-14
 */
@RestController
@RequestMapping("/medicine/medicineStocks")
public class DocStocksController extends BaseController
{

    @Autowired
    private ISysDictTypeService dictTypeService;


    @Autowired
    private IDocStocksService docStocksService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询商品库存列表
     */
    @PreAuthorize("@ss.hasPermi('medicine:medicineStocks:list')")
    @GetMapping("/list")
    public TableDataInfo list(DocStocks docStocks)
    {
        // 构建缓存键，包含分页参数和查询条件
        String cacheKey = buildCacheKey("medicine_stocks_list", docStocks);

        try {
            // 尝试从Redis缓存获取数据
            String cachedJson = (String) redisTemplate.opsForValue().get(cacheKey);
            if (cachedJson != null && !cachedJson.isEmpty()) {
                // 如果缓存中有数据，将其从JSON转换为TableDataInfo对象
                TableDataInfo cachedData = JSON.parseObject(cachedJson, TableDataInfo.class);
                return cachedData;
            }
        } catch (Exception e) {
            // 如果转换失败，忽略缓存，重新查询数据
            System.err.println("Failed to get or parse cached data: " + e.getMessage());
        }

        startPage();
        List<DocStocks> list = docStocksService.selectDocStocksList(docStocks);
        TableDataInfo result = getDataTable(list);

        // 存入Redis缓存（以JSON格式），缓存1小时
        try {
            String json = JSON.toJSONString(result);
            redisTemplate.opsForValue().set(cacheKey, json, 1, TimeUnit.HOURS);
        } catch (Exception e) {
            // 如果缓存存储失败，仅记录日志，不影响主业务流程
            System.err.println("Failed to cache data: " + e.getMessage());
        }

        return result;
    }

    /**
     * 构建缓存键，包含分页参数和查询条件
     * @param prefix 键前缀
     * @param docStocks 查询条件
     * @return 缓存键
     */
    private String buildCacheKey(String prefix, DocStocks docStocks) {
        StringBuilder keyBuilder = new StringBuilder(prefix);

        // 添加分页参数
        com.ruoyi.common.core.page.PageDomain pageDomain = com.ruoyi.common.core.page.TableSupport.buildPageRequest();
        keyBuilder.append(":pageNum=").append(pageDomain.getPageNum());
        keyBuilder.append(":pageSize=").append(pageDomain.getPageSize());
        keyBuilder.append(":orderBy=").append(pageDomain.getOrderByColumn());
        keyBuilder.append(":isAsc=").append(pageDomain.getIsAsc());

        // 添加查询条件
        if (docStocks != null) {
            if (docStocks.getDrugName() != null && !docStocks.getDrugName().isEmpty()) {
                keyBuilder.append(":drugName=").append(docStocks.getDrugName());
            }
            if (docStocks.getDrugType() != null && !docStocks.getDrugType().isEmpty()) {
                keyBuilder.append(":drugType=").append(docStocks.getDrugType());
            }
            if (docStocks.getDrugState() != null && !docStocks.getDrugState().isEmpty()) {
                keyBuilder.append(":drugState=").append(docStocks.getDrugState());
            }
        }

        return keyBuilder.toString();
    }

    /**
     * 导出商品库存列表
     */
    @PreAuthorize("@ss.hasPermi('medicine:medicineStocks:export')")
    @Log(title = "商品库存", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DocStocks docStocks)
    {
        List<DocStocks> list = docStocksService.selectDocStocksList(docStocks);
        ExcelUtil<DocStocks> util = new ExcelUtil<DocStocks>(DocStocks.class);
        util.exportExcel(response, list, "商品库存数据");
    }

    /**
     * 获取商品库存详细信息
     */
    @PreAuthorize("@ss.hasPermi('medicine:medicineStocks:query')")
    @GetMapping(value = "/{drugId}")
    public AjaxResult getInfo(@PathVariable("drugId") Long drugId)
    {
        return success(docStocksService.selectDocStocksByDrugId(drugId));
    }

    /**
     * 新增商品库存
     */
    @PreAuthorize("@ss.hasPermi('medicine:medicineStocks:add')")
    @Log(title = "商品库存", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DocStocks docStocks)
    {

        return toAjax(docStocksService.insertDocStocks(docStocks));
    }

    /**
     * 修改商品库存
     */
    @PreAuthorize("@ss.hasPermi('medicine:medicineStocks:edit')")
    @Log(title = "商品库存", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DocStocks docStocks)
    {
        // 更新数据时清除相关缓存
        clearRelatedCache();
        return toAjax(docStocksService.updateDocStocks(docStocks));
    }

    /**
     * 删除商品库存
     */
    @PreAuthorize("@ss.hasPermi('medicine:medicineStocks:remove')")
    @Log(title = "商品库存", businessType = BusinessType.DELETE)
    @DeleteMapping("/{drugIds}")
    public AjaxResult remove(@PathVariable Long[] drugIds)
    {
        // 删除数据时清除相关缓存
        clearRelatedCache();
        return toAjax(docStocksService.deleteDocStocksByDrugIds(drugIds));
    }

    /**
     * 清除相关缓存
     */
    private void clearRelatedCache() {
        // 清除列表缓存
        redisTemplate.keys("medicine_stocks_list*").forEach(key -> redisTemplate.delete(key));
    }

    /**
     * 按药品类型分组获取药品列表（带Redis缓存）
     */
    @GetMapping("/listByType")
    public AjaxResult listByType(DocStocks docStocks) {
        String cacheKey = "medicine_stocks_by_type";

        try {
            // 尝试从Redis缓存获取数据
            String cachedJson = (String) redisTemplate.opsForValue().get(cacheKey);
            if (cachedJson != null && !cachedJson.isEmpty()) {
                // 如果缓存中有数据，将其从JSON转换为Map对象
                Map<String, List<MedicineOption>> cachedData = JSON.parseObject(cachedJson, new TypeReference<Map<String, List<MedicineOption>>>(){});
                return AjaxResult.success(cachedData);
            }
        } catch (Exception e) {
            // 如果转换失败，忽略缓存，重新查询数据
            System.err.println("Failed to get or parse cached data: " + e.getMessage());
        }

        // 获取药品类型字典
        List<SysDictData> medicineTypeDict = dictTypeService.selectDictDataByType("medicine_type");

        // 创建类型值到标签的映射
        Map<String, String> typeValueToLabelMap = new HashMap<>();
        if (medicineTypeDict != null) {
            for (SysDictData dictData : medicineTypeDict) {
                typeValueToLabelMap.put(dictData.getDictValue(), dictData.getDictLabel());
            }
        }

        // 查询所有药品数据
        List<DocStocks> allMedicines = docStocksService.selectDocStocksList(docStocks);

        // 按类型分组
        Map<String, List<MedicineOption>> groupedData = allMedicines.stream()
                .collect(Collectors.groupingBy(
                        med -> {
                            // 使用字典标签作为分组键，如果没有对应的标签则使用原始值
                            String typeValue = med.getDrugType();
                            return typeValueToLabelMap.getOrDefault(typeValue, typeValue);
                        },
                        Collectors.mapping(med -> new MedicineOption(med.getDrugId(), med.getDrugName()),
                                Collectors.toList())
                ));

        // 存入Redis缓存（以JSON格式）
        try {
            String json = JSON.toJSONString(groupedData);
            redisTemplate.opsForValue().set(cacheKey, json, 1, TimeUnit.DAYS);
        } catch (Exception e) {
            // 如果缓存存储失败，仅记录日志，不影响主业务流程
            System.err.println("Failed to cache data: " + e.getMessage());
        }

        return AjaxResult.success(groupedData);
    }

}
